package com.tuo51.childcare.service.impl;

import com.tuo51.childcare.domain.dailyrecord.DailyGrowRecord;
import com.tuo51.childcare.domain.dailyrecord.DailyGrowRecordTemplate;
import com.tuo51.childcare.domain.dailytask.DailyTask;
import com.tuo51.childcare.domain.dailytask.DailyTaskTemplate;
import com.tuo51.childcare.domain.vo.DailyGrowRecordVO;
import com.tuo51.childcare.domain.vo.DailyTaskTemplateGroupVO;
import com.tuo51.childcare.domain.vo.DailyTaskTemplateMeta;
import com.tuo51.childcare.domain.vo.DailyTaskTemplateVO;
import com.tuo51.childcare.repository.DailyGrowRecordRepository;
import com.tuo51.childcare.repository.DailyGrowRecordTemplateRepository;
import com.tuo51.childcare.repository.DailyTaskRepository;
import com.tuo51.childcare.repository.DailyTaskTemplateRepository;
import com.tuo51.childcare.service.DailyService;
import com.tuo51.childcare.service.FeedsService;
import com.tuo51.evaluate.domain.childrens.Children;
import com.tuo51.evaluate.domain.evaluatingV2.EvaluateV2Record;
import com.tuo51.evaluate.domain.evaluatingV2.EvaluateV2RecordDimensionScore;
import com.tuo51.core.domain.staffs.Staff;
import com.tuo51.evaluate.service.ChildrenService;
import com.tuo51.evaluate.service.EvaluateV2Service;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DailyServiceImpl implements DailyService {

    @Autowired
    DailyTaskTemplateRepository taskTemplateRepository;

    @Autowired
    DailyGrowRecordTemplateRepository obTemplateRepository;

    @Autowired
    DailyGrowRecordRepository growRecordRepository;

    @Autowired
    DailyTaskRepository taskRepository;

    @Autowired
    EvaluateV2Service evaluateV2Service;

    @Autowired
    ChildrenService childrenService;

    @Autowired
    FeedsService feedsService;

    @Override
    public List<DailyGrowRecordTemplate> dailyGrowRecordTemplates(Staff staff) {
        //获取默认宝宝
        //0.数字，1.文字，2.时间 3.时长 4.文件，5.单选，6.多选
        Children c = childrenService.defaultChildrenForParent(staff);
        Integer month = 28;
        if (c != null){
            month = DateUtil.betweenMonths(new Date(), c.getBirthday());
        }

        //找到今天的，所有数据，然后
        List<DailyGrowRecordTemplate> ret = obTemplateRepository.findDailyTemplates(month);

        List<String> templateIds = ret.stream().map(k->k.getId()).collect(Collectors.toList());

        List<DailyGrowRecord> values = growRecordRepository.findDailyValues(staff.getId(), c.getId(), DateUtil.formatDayToStr(new Date()), templateIds);

        Map<String, List<DailyGrowRecordVO>> cache = new HashMap<>();
        values.stream().forEach(k ->{
            List<DailyGrowRecordVO> list = cache.get(k.getTemplateId());
            if (list == null){
                list = new ArrayList<>();
                cache.put(k.getTemplateId(), list);
            }
            list.add(DailyGrowRecordVO.of(k));
        });

        ret.stream().forEach(k->k.setValues(cache.get(k.getId())));

        return ret;
    }

    @Override
    public List<DailyGrowRecordVO> saveGrowRecord(Staff staff, List<DailyGrowRecordVO> values) {
        List<DailyGrowRecord> batch = new ArrayList<>();

        Children children = childrenService.defaultChildrenForParent(staff);

        String cid = children == null?null:children.getId();
        for (DailyGrowRecordVO ob : values ){
            DailyGrowRecordTemplate template = obTemplateRepository.getOne(ob.getTemplateId());

            DailyGrowRecord observer = null;
            if (!template.getRepeatable()){
                //不能重复的观测
                //找到之前的记录
                List<DailyGrowRecord> obs = growRecordRepository.findDailyValue(staff.getId(), cid, DateUtil.formatDayToStr(new Date()), template.getId());
                if (obs != null && obs.size() > 0){
                    observer = obs.get(0);
                }
            }

            if (observer == null){
                observer = new DailyGrowRecord();
                observer.setDailyIndex(template.getDailyIndex());
                observer.setTemplateId(template.getId());
                observer.setTitle(template.getTitle());
                observer.setUid(staff.getId());
                observer.setChildrenId(cid);
                observer.setDay(DateUtil.formatDayToStr(new Date()));
            }

            observer.setValue(ob.getValue());

            growRecordRepository.save(observer);
            batch.add(observer);

            //发送feeds
            feedsService.postFeeds(staff, children, template.getTitle(), ob.getValue(), null, null, FeedsService.FeedsType.FeedGrowRecord, observer.getId());
        }


        return batch.stream().map(k-> DailyGrowRecordVO.of(k)).collect(Collectors.toList());
    }


    @Override
    public List<DailyTaskTemplateGroupVO> taskTemplates(Staff staff, String reportId) {
        //找到报告
        EvaluateV2Record report = evaluateV2Service.getEvaluateDetail(reportId);

        //找到低于分数的能区
        //List<String> ids = report.getDimensionScores().stream().filter(k -> k.getDq() < 900).map(k->k.getId()).collect(Collectors.toList());
        //Integer month = report.getMonth();

        List<DailyTaskTemplateGroupVO> ret = new ArrayList<>();
        for(EvaluateV2RecordDimensionScore score : report.getDimensionScores()){

            log.info("query task template " + score.getMonth()/10  + "|||" + score.getDq()  + "|||" + score.getDimensionId());
            List<DailyTaskTemplate> dimensionTaskTemplates = taskTemplateRepository.findDimensionTaskTemplates( score.getMonth()/10, score.getDq(), score.getDimensionId());

            if (dimensionTaskTemplates == null || dimensionTaskTemplates.size()  == 0){
                continue;
            }

            ret.add(DailyTaskTemplateGroupVO.of(score.getDimensionName(),
                    score.getDimensionId(),
                    dimensionTaskTemplates.stream().map(k-> DailyTaskTemplateVO.of(k)).collect(Collectors.toList())
            ));

        }

        return ret;
    }

    @Override
    @Transactional
    public boolean savePlan(Staff staff, List<String> templateIds) {

        Children children = childrenService.defaultChildrenForParent(staff);
        //删除当前用户今天以后的所有任务；
        taskRepository.deleteAllByUidAndChildrenIdAndScheduleGreaterThanAndFinishedIsFalse(staff.getId(), children.getId(), new Date());

        //创建未来的任务
        List<DailyTask> tasks = new ArrayList<>();

        List<DailyTaskTemplate> templates = taskTemplateRepository.findAllById(templateIds);

        Date today = new Date();
        int weekOffset = 0;
        for (DailyTaskTemplate template : templates){
            //计算日期

            DailyTaskTemplateMeta meta = template.getPlanMeta();
            if (meta == null){
                //应用默认 meta
                meta = DailyTaskTemplateMeta.dayPerMonth(1);
                template.setPlanMeta(meta);
                taskTemplateRepository.save(template);
            }

            //TODO：需要处理不同人物间的偏移
            for (int i = 0; i < meta.getDurationDays(); i += meta.getPerDay()){

//                final int loopCount = meta.getTimes();
                int step =(int) (meta.getPerDay() * 1.0 / meta.getTimes() + 0.5);

                if (step <= 1){
                    step = 1;
                }

                for (int loop = 0; loop < meta.getPerDay() && i+loop < meta.getDurationDays(); loop += step){
                    //创建任务
                    DailyTask task = DailyTask.of(template);
                    task.setSchedule(DateUtil.plusDaysToDate(today, i + loop));
                    task.setUid(staff.getId());
                    task.setChildrenId(children.getId());
                    tasks.add(task);
                }
            }
        }
        taskRepository.saveAll(tasks);

        return true;
    }

    @Override
    public List<DailyTask> dailyTask(Staff staff) {
        Children children = childrenService.defaultChildrenForParent(staff);
        String uid = staff.getId();
        String cid = children.getId();
        return taskRepository.findUserDailyTasks(uid, cid, new Date());
    }

    @Override
    public DailyTask finishTask(Staff staff, String taskId) {

        Children children = childrenService.defaultChildrenForParent(staff);

        DailyTask task = taskRepository.getOne(taskId);

        if (task == null){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "任务不存在");
        }

        if (task.getFinished()){
            throw new BusinessException(ErrorCode.TASK_ALREADY_FINISHED, "任务已经完成过了");
        }
        task.setFinished(true);
        task.setFinishedAt(new Date());

        taskRepository.save(task);

        feedsService.postFeeds(staff, children, task.getTitle(), "", null, null, FeedsService.FeedsType.FeedDailyTask, task.getId());

        return task;
    }

}
